package org.autumn.jmm;

public class Disorder {

    private static int x = 0;
    private static int y = 0;
    private static int a = 0;
    private static int b = 0;

    public static void main(String[] args) throws InterruptedException {
        int i = 0;
        for (; ; ) {
            i++;
            a = 0;
            b = 0;
            x = 0;
            y = 0;

            Thread t1 = new Thread(new Runnable() {
                @Override
                public void run() {
                    a = 1;
                    x = b;  //指令重排 先执行这个代码,导致x = 0 y = 0
                }
            });

            Thread t2 = new Thread(new Runnable() {
                @Override
                public void run() {
                    b = 1;
                    y = a;   //指令重排 先执行这个代码,导致x = 0 y = 0
                }
            });
            t1.start();
            t2.start();
            t1.join();
            t2.join();
            /**
             * 我们在正常情况下 x y的值组合
             * x = 0  y = 1
             * x = 1  y = 0
             * x = 1  y = 1
             * 不可能出现 x = 0 y = 0的情况 除非发生指令重排
             *
             *
             * 第188455次 (0,1)
             * 第188456次 (0,1)
             * 第188457次 (0,1)
             * 第188458次 (0,1)
             * 第188459次 (0,0)
             */
            String result = "第" + i + "次 (" + x + "," + y + ")";
            if (x == 0 && y == 0){
                System.err.println(result);
                break;
            }else {
                System.out.println(result);
            }
        }
    }
}
